package com.macro.mall.tiny.modules.pms.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonPage;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.util.ImageUtil;
import com.macro.mall.tiny.modules.pms.dto.ProductSkuAttrValueParam;
import com.macro.mall.tiny.modules.pms.dto.ProductSkuParam;
import com.macro.mall.tiny.modules.pms.dto.ProductSkuQueryParam;
import com.macro.mall.tiny.modules.pms.dto.ProductSkuResponse;
import com.macro.mall.tiny.modules.pms.model.ProductSku;
import com.macro.mall.tiny.modules.pms.service.ProductSkuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.security.PermitAll;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@Tag(name = "ProductSkuController", description = "商品SKU管理")
@RequestMapping("/product-sku")
@PermitAll  // 类级别放行所有方法
public class ProductSkuController {

    @Autowired
    private ProductSkuService productSkuService;

    @Autowired
    private ImageUtil imageUtil;

    @Operation(summary = "分页查询商品SKU")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<ProductSkuResponse>> list(ProductSkuQueryParam queryParam) {
        // 设置默认分页参数
        if (queryParam.getPageNum() == null) {
            queryParam.setPageNum(1);
        }
        if (queryParam.getPageSize() == null) {
            queryParam.setPageSize(5);
        }

        Page<ProductSku> productSkuList;
        // 特殊处理属性值查询
        if (StringUtils.hasText(queryParam.getPvValue())) {
            // 需要关联查询SKU和属性值表
            productSkuList = productSkuService.listWithAttrValue(queryParam, queryParam.getPageSize(), queryParam.getPageNum());
        } else {
            productSkuList = productSkuService.list(queryParam, queryParam.getPageSize(), queryParam.getPageNum());
        }

        // Convert ProductSku entities to ProductSkuResponse DTOs
        List<ProductSkuResponse> responseList = productSkuList.getRecords().stream().map(sku -> {
            // Format main image URL
            if (sku.getMainImg() != null) {
                sku.setMainImg(imageUtil.buildImageUrl(sku.getMainImg()));
            }

            // Convert to response DTO
            ProductSkuResponse response = new ProductSkuResponse();
            BeanUtils.copyProperties(sku, response);
            return response;
        }).collect(Collectors.toList());

        // Batch fetch attribute values for all SKUs
        List<Integer> skuIds = responseList.stream()
                .map(ProductSkuResponse::getSkuId)
                .collect(Collectors.toList());

        // Fetch all attribute values in batch
        Map<Integer, List<ProductSkuAttrValueParam>> attrValueMap =
                productSkuService.batchGetAttrValues(skuIds);

        // Assign attribute values to each response
        responseList.forEach(response -> {
            response.setAttrValueList(attrValueMap.getOrDefault(response.getSkuId(), new ArrayList<>()));
        });

        // Create new page with ProductSkuResponse objects
        Page<ProductSkuResponse> responsePage = new Page<>(productSkuList.getCurrent(), productSkuList.getSize(), productSkuList.getTotal());
        responsePage.setRecords(responseList);

        return CommonResult.success(CommonPage.restPage(responsePage));

    }


    @Operation(summary = "创建商品SKU")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Void> create(@Validated @RequestBody ProductSkuParam productSkuParam) {
        boolean success = productSkuService.create(productSkuParam);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @Operation(summary = "根据ID获取商品SKU详情")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<ProductSkuResponse> getItem(@PathVariable Long id) {
        ProductSkuResponse productSku = productSkuService.getDetailItem(id);
        if (productSku == null) {
            return CommonResult.failed("商品SKU不存在");
        }
        productSku.setMainImg(imageUtil.buildImageUrl(productSku.getMainImg()));
        return CommonResult.success(productSku);
    }


    @Operation(summary = "更新商品SKU信息")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Void> update(@PathVariable Long id, @RequestBody ProductSkuParam productSkuParam) {
        boolean success = productSkuService.update(id, productSkuParam);
        if (success) {
            return CommonResult.success(null);
        }
        return CommonResult.failed();
    }

    @Operation(summary = "删除商品SKU信息")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Boolean> delete(@PathVariable Integer id) {
        boolean success = productSkuService.delete(id);
        if (success) {
            return CommonResult.success(success);
        }
        return CommonResult.failed();
    }


}
